import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'

Vue.use(VueRouter)

const routes = [
  {
    // 布局骨架
    path: '/',
    component: () => import('@/views/layout.vue'),
    children: [
      {
        // 首页
        path: '/',
        component: () => import('@/views/home/index.vue')
      },
      {
        // 问答
        path: '/question',
        component: () => import('@/views/question/index.vue')
      },
      {
        // 视频
        path: '/video',
        component: () => import('@/views/video/index.vue')
      },
      {
        // 个人中心
        path: '/user',
        component: () => import('@/views/profile/index.vue')
      }
    ]
  },
  {
    // 登录
    path: '/login',
    component: () => import('@/views/login/index.vue')
  },
  {
    // 编辑资料
    path: '/user/profile',
    component: () => import('@/views/user/edit.vue')
  },
  {
    // 聊天功能
    path: '/user/chat',
    component: () => import('@/views/user/chat.vue')
  },
  {
    // 搜索
    path: '/search',
    component: () => import('@/views/search/index.vue')
  },
  {
    // 搜索结果
    path: '/search/result',
    component: () => import('@/views/search/result.vue')
  },
  {
    // 文章详情
    path: '/article/:id',
    component: () => import('@/views/article/index.vue')
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const { user } = store.state
  if (to.path.startsWith('/user') && !user.token) {
    next(`/login?redirectUrl=${to.path}`)
  } else {
    next()
  }
})

export default router
